package com.serverapk;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.media.MediaPlayer;

import com.google.gson.Gson;
import com.serverapk.camera.CameraService;
import com.serverapk.camera.ImgChange;
import com.serverapk.interfaces.OkHttpCallbackListener;
import com.serverapk.model.CachedThreadFactory;
import com.serverapk.model.ListData;
import com.serverapk.model.VideoData;
import com.serverapk.para.Common;
import com.serverapk.util.L;
import com.serverapk.util.NexUtil;
import com.serverapk.util.SPUtils;
import com.serverapk.util.Tool;

//import net.sf.json.JSONArray;
//import net.sf.json.JSONObject;
import org.json.JSONArray;
import org.json.JSONObject;

import org.greenrobot.eventbus.EventBus;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;


public class PostNex {
    public static boolean initFlag = false;
    public static boolean heartFlag = true;
    public Context context;
    private static CameraService cameraService = new CameraService();

    public PostNex(Context context) {
        this.context = context;
    }

    //获取版本号
    private int getNativeVersionCode() {
        try {
            PackageInfo pi = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
            return pi.versionCode;
        } catch (Exception e) {
            // TODO Auto-generated catch block  
            e.printStackTrace();
            return -1;
        }
    }

    /**
     * 获取启动参数
     */
    public static void initPost(final String lon, final String lat) {
        L.e("**********initPost**********");
        new Thread(new Runnable() {

            @Override
            public void run() {
                HashMap<String, Object> params = new HashMap<>();
                params.put("appid", Common.appId);
                params.put("version", Common.version);
                params.put("timestamp", new Date().getTime() / 1000 + "");
                params.put("imei", Common.imei);
                params.put("longitude", lon);
                params.put("latitude", lat);
                String sign;
                try {
                    sign = NexUtil.signature(params, Common.appSecret);
                    params.put("sign", sign);
                } catch (Exception e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
                L.e("init:" + params.toString());
                String result = NexUtil.sendPost(Common.initUrl, params);
                L.e("**********initPost**********" + result);
                if (result != null && !"".equals(result)) {
                    setPara(result);
                }
            }
        }).start();
    }

    /**
     * 获取上传OSS地址
     */
    public static void getOssUrl(final String name, final String contentType) {
        CachedThreadFactory.getInstance().addTask(name + "", new Runnable() {
            @Override
            public void run() {
                HashMap<String, Object> params = new HashMap<>();
                params.put("appid", Common.appId);
                params.put("name", name);
                params.put("contentType", contentType);
                params.put("version", Common.version);
                params.put("timestamp", new Date().getTime() / 1000 + "");
                params.put("imei", Common.imei);
//                params.put("imei","869566020656484");
                String sign;
                try {
                    sign = NexUtil.signature(params, Common.appSecret);
                    params.put("sign", sign);
                } catch (Exception e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
                L.e("请求参数：" + params.toString());
                String result = NexUtil.sendPost(Common.getOssUrl, params);

                EventBus.getDefault().post(result);
                L.e("上传OSS地址返回：" + result);
            }
        });
    }

    /**
     * 刷卡开门
     */
    public static void cardPost(final String cardnum, final String cardsnr, final String money) {

        CachedThreadFactory.getInstance().addTask(System.currentTimeMillis() + "", new Runnable() {
            @Override
            public void run() {
                HashMap<String, Object> params = new HashMap<>();
                params.put("appid", Common.appId);
                params.put("version", Common.version);
                params.put("timestamp", new Date().getTime() / 1000 + "");
                params.put("imei", Common.imei);
//                params.put("imei","869566020656484");
                params.put("cardnum", cardnum);
                params.put("cardsnr", cardsnr);
//                params.put("money", money);
                String sign;
                try {
                    sign = NexUtil.signature(params, Common.appSecret);
                    params.put("sign", sign);
                } catch (Exception e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
                L.e("请求参数：" + params.toString());
                String result = NexUtil.sendPost(Common.cardUrl, params);

                EventBus.getDefault().post(result);
                L.e("刷卡开门返回：" + result);
            }
        });

    }

    /***
     * 获取清单列表
     */
    public static void getList(final String sid, final String boxid) {
        CachedThreadFactory.getInstance().addTask(boxid, new Runnable() {
            @Override
            public void run() {
                //创建OkHttpClient对象
                OkHttpClient okHttpClient = new OkHttpClient.Builder().build();
                Request request = new Request.Builder()
                        .get()
                        .url(Common.getListUrl + "?sid=" + sid + "&boxid=" + boxid)
                        .build();

                L.e("getList:" + request.toString());
                okHttpClient.newCall(request).enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        L.e("获取清单列表失败：" + e.toString());
                        CachedThreadFactory.getInstance().removeTask(boxid);
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        CachedThreadFactory.getInstance().removeTask(boxid);
                        Gson gson = new Gson();

                        String str = response.body().string();
                        L.e("获取清单列表：" + str);
                        ListData listData = gson.fromJson(str, ListData.class);
                        EventBus.getDefault().post(listData);
                    }
                });
            }
        });
    }

    /***
     * 获取视频/图片
     */
    public static void getVideo(final String sid, final String boxid) {
        CachedThreadFactory.getInstance().addTask(boxid + "=", new Runnable() {
            @Override
            public void run() {
                //创建OkHttpClient对象
                OkHttpClient okHttpClient = new OkHttpClient.Builder().build();
                Request request = new Request.Builder()
                        .get()
                        .url(Common.getVideoUrl + "?sid=" + sid + "&boxid=" + boxid)
                        .build();
                L.e("getVideo:" + request.toString());
                okHttpClient.newCall(request).enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        L.e("获取视频列表失败：" + e.toString());
                        CachedThreadFactory.getInstance().removeTask(boxid + "=");
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
//                        L.e("获取清单列表：" + response.body().string());
                        CachedThreadFactory.getInstance().removeTask(boxid + "=");
                        Gson gson = new Gson();

                        String str = response.body().string();
                        L.e("获取视频列表：" + str);
                        VideoData videoData = gson.fromJson(str, VideoData.class);
                        EventBus.getDefault().post(videoData);
                    }
                });
            }
        });
    }

    public static void setPara(String result) {

        try {
//        JSONObject jsonObject = JSONObject.fromObject(result);
            JSONObject jsonObject = new JSONObject(result);
            String code = jsonObject.getString("code");
            String msg = jsonObject.getString("msg");
            System.out.println(code + msg);
            if ("10000".equals(code)) {

                JSONObject data = jsonObject.getJSONObject("data");
                Common.type = data.getInt("type");
                Common.dev_id = data.getString("dev_id");

                JSONObject mqtt_jsonObject = data.getJSONObject("mqtt");
                Common.instance_id = mqtt_jsonObject.getString("instance_id");
                Common.topic = mqtt_jsonObject.getString("topic");
                Common.group_id = mqtt_jsonObject.getString("group_id");
                Common.mqtt_host = mqtt_jsonObject.getString("host");
                Common.mqtt_port = mqtt_jsonObject.getString("port");
                Common.mqtt_access_key = mqtt_jsonObject.getString("access_key");
                Common.mqtt_secret_key = mqtt_jsonObject.getString("secret_key");
                Common.md5 = mqtt_jsonObject.getString("md5");


                JSONObject cameral_jsonObject = data.getJSONObject("detect_model");
                //TODO 刚改的 写死url
//                Common.camera_url = "https://deploy.seetatech.com/api";

                Common.camera_url = cameral_jsonObject.getString("url");
                L.e("url=======" + Common.camera_url);

                Common.camera_api_key = cameral_jsonObject.getString("api_key");
                Common.camera_secret_key = cameral_jsonObject.getString("secret_key");

                Common.cameraIp.clear();
                JSONArray jsonArray = data.getJSONArray("cameras");
//                for (int i = 0; i < jsonArray.size(); i++) {
                for (int i = 0; i < jsonArray.length(); i++) {
                    Common.cameraIp.add(jsonArray.getString(i));
                }

                JSONObject img_jsonObject = data.getJSONObject("image_size");
                Common.max_width = img_jsonObject.getInt("max_width");
                Common.max_height = img_jsonObject.getInt("max_height");
                Common.heartTime = data.getInt("heartbeat_time");
                Common.serverTime = data.getInt("server_time");
                initFlag = true;

                JSONObject oss_jsonObject = data.getJSONObject("oss");
                Common.endPoint = oss_jsonObject.getString("endPoint");
                Common.url = oss_jsonObject.getString("url");
                Common.accessKey = oss_jsonObject.getString("accessKey");
                Common.secretKey = oss_jsonObject.getString("secretKey");
                Common.bucketName = oss_jsonObject.getString("bucketName");

                EventBus.getDefault().post("ping");
            }
        } catch (Exception e) {
            L.e("setPara error:" + e.toString());
        }
    }

    /**
     * 算法结果通知
     * result 识别接口的识别结果
     * remoteUrl 成功上传到OSS的视频文件名
     */
    public static void notifyPostVideo(final List<String> result, final String remoteUrl, final String seq) {
        new Thread(new Runnable() {

            @Override
            public void run() {
                HashMap<String, Object> params = new HashMap<>();
                params.put("appid", Common.appId);
                params.put("version", Common.version);
                params.put("timestamp", new Date().getTime() / 1000 + "");
                params.put("imei", Common.imei);
//                if ((boolean) SPUtils.get(BaseApplication.mContext, "isUploadSuc", true)) {
                params.put("seq", seq);
//                } else {
//                    params.put("seq", (String) SPUtils.get(BaseApplication.mContext, "seq", ""));
//                }
                if (Common.type == 1)
                    params.put("result", result);
                else if (Common.type == 2)
                    params.put("result", remoteUrl);
                String sign;
                try {
                    sign = NexUtil.signature(params, Common.appSecret);
                    params.put("sign", sign);
                } catch (Exception e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }

                String result = NexUtil.sendPost(Common.notifyUrl, params);
                L.e("结果=" + result);
                if (Common.type == 1) {
                    PostNex.imagePost();
                }

            }
        }).start();
    }

    /**
     * 算法结果通知
     * result 识别接口的识别结果
     * remoteUrl 成功上传到OSS的视频文件名
     */
    public static void notifyPost(final List<String> result, final String remoteUrl) {
        new Thread(new Runnable() {

            @Override
            public void run() {
                HashMap<String, Object> params = new HashMap<>();
                params.put("appid", Common.appId);
                params.put("version", Common.version);
                params.put("timestamp", new Date().getTime() / 1000 + "");
                params.put("imei", Common.imei);
//                if ((boolean) SPUtils.get(BaseApplication.mContext, "isUploadSuc", true)) {
                params.put("seq", Common.seq);
//                } else {
//                    params.put("seq", (String) SPUtils.get(BaseApplication.mContext, "seq", ""));
//                }
                if (Common.type == 1)
                    params.put("result", result);
                else if (Common.type == 2)
                    params.put("result", remoteUrl);
                String sign;
                try {
                    sign = NexUtil.signature(params, Common.appSecret);
                    params.put("sign", sign);
                } catch (Exception e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }

                String result = NexUtil.sendPost(Common.notifyUrl, params);
                L.e("结果=" + result);
                if (Common.type == 1) {
                    PostNex.imagePost();
                }
                System.out.println("**********notifyPost**********" + result);

            }
        }).start();
    }


    /**
     * 算法结果通知
     */
//    public static void notifyPost(final List<String> result, final List<String> imgList) {
//        new Thread(new Runnable() {
//
//            @Override
//            public void run() {
//                HashMap<String, Object> params = new HashMap<>();
//                params.put("appid", Common.appId);
//                params.put("version", Common.version);
//                params.put("timestamp", new Date().getTime() / 1000 + "");
//                params.put("imei", Common.imei);
//                params.put("seq", Common.seq);
//                params.put("result", result);
//                String sign;
//                try {
//                    sign = NexUtil.signature(params, Common.appSecret);
//                    params.put("sign", sign);
//                } catch (Exception e1) {
//                    // TODO Auto-generated catch block
//                    e1.printStackTrace();
//                }
//                String result = NexUtil.sendPost(Common.notifyUrl, params);
//                System.out.println("**********notifyPost**********" + result);
//
//                if (BaseApplication.getInstance().flag) {
//                    BaseApplication.getInstance().flag = false;
//                    sendPic(imgList);
//                }
//
//            }
//        }).start();
//    }

    /**
     * 图片上传
     */
    public static void imagePost() {
        L.e("99====================");
        new Thread(new Runnable() {

            @Override
            public void run() {
                LinkedHashMap<String, String> files = ImgChange.getFiles(Common.filepath);
                L.e("**********filessize********" + files.size());
                Map<String, String> imgMap = new HashMap<String, String>();
                int i = 0;
                for (String fileName : files.keySet()) {
//                    System.out.println("**********imgFilePath************" + files.get(fileName));
                    L.e("**********imgFilePath********" + files.get(fileName));
                    imgMap.put(Common.cameraIp.get(i), Tool.GetImageStr_Base64(files.get(fileName)));
                    i++;
                }
//                System.out.println("**********imgMap********" + imgMap.size());
                L.e("**********imgMap********" + imgMap.size());
//                JSONObject jsonObject = JSONObject.fromObject(imgMap);
                JSONObject jsonObject = new JSONObject(imgMap);
                String imgStr = jsonObject.toString();
//                System.out.println("**********imgStr********" + imgStr);
                L.e("**********imgStr********" + imgStr);
                HashMap<String, Object> params = new HashMap<>();
                params.put("appid", Common.appId);
                params.put("version", Common.version);
                params.put("timestamp", new Date().getTime() / 1000 + "");
                params.put("imei", Common.imei);
                params.put("seq", Common.seq);
                String sign;
                try {
                    sign = NexUtil.signature(params, Common.appSecret);
                    params.put("sign", sign);
                    params.put("images", imgStr);
                } catch (Exception e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
                String result = NexUtil.sendPost(Common.imageUrl, params);
                L.e("imgpost结果：" + result);
                System.out.println("**********imagePost**********" + result);
            }
        }).start();
    }

    /**
     * 状态上报
     */
    public static void statusPost(final int lock_status, final int door_status) {
        new Thread(new Runnable() {

            @Override
            public void run() {
                HashMap<String, Object> params = new HashMap<>();
                params.put("appid", Common.appId);
                params.put("version", Common.version);
                params.put("timestamp", new Date().getTime() / 1000 + "");
                params.put("imei", Common.imei);
                params.put("seq", Common.seq);
                params.put("door_status", door_status);
                params.put("lock_status", lock_status);
                String sign;
                try {
                    sign = NexUtil.signature(params, Common.appSecret);
                    params.put("sign", sign);
                } catch (Exception e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
                String result = NexUtil.sendPost(Common.statusUrl, params);
                System.out.println("**********statusPost**********" + result);
            }
        }).start();
    }

    /**
     * 错误上报
     */
    public static void errorPost(final int code, final String error) {
        new Thread(new Runnable() {

            @Override
            public void run() {
                HashMap<String, Object> params = new HashMap<>();
                params.put("appid", Common.appId);
                params.put("version", Common.version);
                params.put("timestamp", new Date().getTime() / 1000 + "");
                params.put("imei", Common.imei);
//                if ((boolean) SPUtils.get(BaseApplication.mContext, "isUploadSuc", true)) {
                params.put("seq", Common.seq);
//                } else {
//                    params.put("seq", (String) SPUtils.get(BaseApplication.mContext, "seq", ""));
//                }
                params.put("code", code);
                params.put("info", error);
                String sign;
                try {
                    sign = NexUtil.signature(params, Common.appSecret);
                    params.put("sign", sign);
                } catch (Exception e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
                String result = NexUtil.sendPost(Common.errorUrl, params);
                L.e("**********errorPost**********" + result);
            }
        }).start();
    }


    private MediaPlayer mediaPlayer;
    private boolean isFirst = true;

    public void heartPost() {
        CachedThreadFactory.getInstance().addTask(System.currentTimeMillis() + "", new Runnable() {
            @Override
            public void run() {
                if (isFirst) {
                    isFirst = false;
                    mediaPlayer = MediaPlayer.create(context, R.raw.xintiao);
                    mediaPlayer.start();
                }
                Common.app_version = getNativeVersionCode();
                HashMap<String, Object> params = new HashMap<>();
                params.put("appid", Common.appId);
                params.put("version", Common.version);
                params.put("timestamp", new Date().getTime() / 1000 + "");
                params.put("imei", Common.imei);
                params.put("app_version", Common.app_version);
                String sign;
                try {
                    sign = NexUtil.signature(params, Common.appSecret);
                    params.put("sign", sign);
                } catch (Exception e1) {
                    L.e("ei:" + e1.toString());
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
                L.e("心跳参数：" + params.toString());
                String result = NexUtil.sendPost(Common.heartUrl, params);
                L.e("**********heartPost**********" + result);
            }
        });


//        new Thread(new Runnable() {
//            @Override
//            public void run() {
//                while (heartFlag) {
////                    if (isFirst) {
////                        isFirst = false;
////                        mediaPlayer = MediaPlayer.create(context, R.raw.xintiao);
////                        mediaPlayer.start();
////                    }
//                    Common.app_version = getNativeVersionCode();
//                    HashMap<String, Object> params = new HashMap<>();
//                    params.put("appid", Common.appId);
//                    params.put("version", Common.version);
//                    params.put("timestamp", new Date().getTime() / 1000 + "");
//                    params.put("imei", Common.imei);
//                    params.put("app_version", Common.app_version);
//                    String sign;
//                    try {
//                        sign = NexUtil.signature(params, Common.appSecret);
//                        params.put("sign", sign);
//                    } catch (Exception e1) {
//                        // TODO Auto-generated catch block
//                        e1.printStackTrace();
//                    }
//                    L.e("心跳参数：" + params.toString());
//                    String result = NexUtil.sendPost(Common.heartUrl, params);
//                    L.e("**********heartPost**********" + result);
//                    try {
//                        Thread.sleep(Common.heartTime * 1000);
//                    } catch (InterruptedException e) {
//                        // TODO Auto-generated catch block
//                        e.printStackTrace();
//                    }
//                }
//            }
//        }).start();

    }


    public static void sendPic(List<String> imgList) {
        // 发送图片至服务器
        cameraService.sendPicture(imgList, new OkHttpCallbackListener() {

            @Override
            public void onFinish(List<String> response) {
                // 算法服务器返回结果response
                // 结果上报后台服务器Common.nex_url
                PostNex.notifyPost(response, "");
                ImgChange.changImg();
                PostNex.imagePost();
            }

            @Override
            public void onError(int code, String e) {
                //上送算法服务器异常
                PostNex.errorPost(code, e);
            }
        });
    }
}
